package com.h3bpm.starcharge.common.uitl.k3c;

import com.google.gson.Gson;
import com.h3bpm.starcharge.common.bean.JsonResult;
import com.h3bpm.starcharge.common.bean.RestfulErrorCode;
import com.h3bpm.starcharge.common.bean.RetResult;
import com.h3bpm.starcharge.common.uitl.RedisUtil;
import com.h3bpm.starcharge.config.K3CloundConfig;
import com.h3bpm.starcharge.ret.k3c.K3cBase;
import com.h3bpm.starcharge.ret.k3c.K3cBaseRet;
import com.h3bpm.starcharge.service.k3c.K3cService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * K3C工具
 *
 * @author LLongAgo
 * @date 2019/3/8
 * @since 1.0.0
 */
@Repository
public class K3cUtil {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private K3cService k3cService;
    @Autowired
    private K3CloundConfig k3CloundConfig;

    @Value("${k3c_API_URL}")
    private String apiUrl;
    @Value("${k3c_dbId}")
    private String dbId;
    @Value("${k3c_uid}")
    private String uid;
    @Value("${k3c_pwd}")
    private String pwd;
    @Value("${k3c_lang}")
    private int lang;

    /**
     * k3c保存
     *
     * @param formId    表单id
     * @param jsonParam json参数
     * @return JsonResult
     * @throws Exception
     */
    public JsonResult<K3cBase> save(String formId, String jsonParam) throws Exception {
        InvokeHelper.POST_K3CloudURL = apiUrl;
        JsonResult<K3cBase> result = new JsonResult<>();
        // k3c登录
        if (InvokeHelper.login(dbId, uid, pwd, lang)) {
            // 调用invoke保存
            String invokeResult = InvokeHelper.save(formId, jsonParam);
            // 将返回结果封装为通用result
            packageResult(invokeResult, result);
        } else {
            packageLoginError(result);
        }
        return result;
    }

    /**
     * k3c下推
     *
     * @param formId    表单id
     * @param jsonParam json参数
     * @return JsonResult
     * @throws Exception
     */
    public JsonResult<K3cBase> push(String formId, String jsonParam) throws Exception {
        InvokeHelper.POST_K3CloudURL = apiUrl;
        JsonResult<K3cBase> result = new JsonResult<>();
        // k3c登录
        if (InvokeHelper.login(dbId, uid, pwd, lang)) {
            // 调用invoke保存
            String invokeResult = InvokeHelper.push(formId, jsonParam);
            // 将返回结果封装为通用result
            packageResult(invokeResult, result);
        } else {
            packageLoginError(result);
        }
        return result;
    }

    /**
     * k3c保存
     *
     * @param formId    表单id
     * @param jsonParam json参数
     * @return JsonResult
     * @throws Exception
     */
    public JsonResult<K3cBase> batchSave(String formId, String jsonParam) throws Exception {
        InvokeHelper.POST_K3CloudURL = apiUrl;
        JsonResult<K3cBase> result = new JsonResult<>();
        // k3c登录
        if (InvokeHelper.login(dbId, uid, pwd, lang)) {
            // 调用invoke批量保存
            String invokeResult = InvokeHelper.batchSave(formId, jsonParam);
            // 将返回结果封装为通用result
            packageResult(invokeResult, result);
        } else {
            System.out.println("登录失败！");
            packageLoginError(result);
        }
        return result;
    }

    /**
     * k3c分配
     *
     * @param formId    表单id
     * @param jsonParam json参数
     * @return JsonResult
     * @throws Exception
     */
    public JsonResult<K3cBase> allocate(String formId, String jsonParam) throws Exception {
        InvokeHelper.POST_K3CloudURL = apiUrl;
        JsonResult<K3cBase> result = new JsonResult<>();

        // k3c登录
        if (InvokeHelper.login(dbId, uid, pwd, lang)) {
            // 调用invoke批量保存
            String invokeResult = InvokeHelper.allocate(formId, jsonParam);
            // 将返回结果封装为通用result
            packageResult(invokeResult, result);
        } else {
            packageLoginError(result);
        }
        return result;
    }

    /**
     * k3c反审核
     *
     * @param formId    表单id
     * @param jsonParam json参数
     * @return JsonResult
     * @throws Exception
     */
    public JsonResult<K3cBase> unAudit(String formId, String jsonParam) throws Exception {
        InvokeHelper.POST_K3CloudURL = apiUrl;
        JsonResult<K3cBase> result = new JsonResult<>();
        // k3c登录
        if (InvokeHelper.login(dbId, uid, pwd, lang)) {
            // 调用invoke批量保存
            String invokeResult = InvokeHelper.unAudit(formId, jsonParam);
            // 将返回结果封装为通用result
            packageResult(invokeResult, result);
        } else {
            packageLoginError(result);
        }
        return result;
    }

    /**
     * k3c提交
     *
     * @param formId    表单id
     * @param jsonParam json参数
     * @return JsonResult
     * @throws Exception
     */
    public JsonResult<K3cBase> submit(String formId, String jsonParam) throws Exception {
        InvokeHelper.POST_K3CloudURL = apiUrl;
        JsonResult<K3cBase> result = new JsonResult<>();
        // k3c登录
        if (InvokeHelper.login(dbId, uid, pwd, lang)) {
            // 调用invoke批量保存
            String invokeResult = InvokeHelper.submit(formId, jsonParam);
            // 将返回结果封装为通用result
            packageResult(invokeResult, result);
        } else {
            packageLoginError(result);
        }
        return result;
    }

    /**
     * k3c审核
     *
     * @param formId    表单id
     * @param jsonParam json参数
     * @return JsonResult
     * @throws Exception
     */
    public JsonResult<K3cBase> audit(String formId, String jsonParam) throws Exception {
        InvokeHelper.POST_K3CloudURL = apiUrl;
        JsonResult<K3cBase> result = new JsonResult<>();
        // k3c登录
        if (InvokeHelper.login(dbId, uid, pwd, lang)) {
            // 调用invoke批量保存
            String invokeResult = InvokeHelper.audit(formId, jsonParam);
            packageResult(invokeResult, result);
        } else {
            packageLoginError(result);
        }
        return result;
    }

    public void delete(String formId, String jsonParam) throws Exception {

        InvokeHelper.POST_K3CloudURL = apiUrl;
        JsonResult<K3cBase> result = new JsonResult<>();
        // k3c登录
        if (InvokeHelper.login(dbId, uid, pwd, lang)) {
            // 调用invoke删除
            InvokeHelper.delete(formId, jsonParam);

        } else {
            packageLoginError(result);
        }

    }

    public String view(String formId, String jsonParam) throws Exception {
        InvokeHelper.POST_K3CloudURL = apiUrl;
        // k3c登录
        if (InvokeHelper.login(dbId, uid, pwd, lang)) {
            return InvokeHelper.view(formId, jsonParam);
        } else {
            throw new Exception("登录失败!");
        }
    }

    public String getList(String jsonParam) throws Exception {
        InvokeHelper.POST_K3CloudURL = apiUrl;
        // k3c登录
        if (InvokeHelper.login(dbId, uid, pwd, lang)) {
            // 调用invoke批量保存
            return InvokeHelper.executeBillQuery(jsonParam);
        } else {
            throw new Exception("登录失败!");
        }
    }

    /**
     * 封装结果
     *
     * @param invokeResult String
     * @param result       JsonResult
     */
    private void packageResult(String invokeResult, JsonResult<K3cBase> result) {
        Gson gson = new Gson();
        K3cBaseRet ret = gson.fromJson(invokeResult, K3cBaseRet.class);
        boolean success = ret.getResult().getResponseStatus().isIsSuccess();
        result.setCode(success ? RestfulErrorCode.SUCCESS.getCode() : RestfulErrorCode.ERROR.getCode());
        if (success) {
            result.setMsg(RestfulErrorCode.SUCCESS.getMsg());
        } else {
            StringBuilder sb = new StringBuilder();
            List<K3cBaseRet.ResultBean.ResponseStatusBean.ErrorsBean> errors = ret.getResult().getResponseStatus().getErrors();
            for (int i = 0; i < errors.size(); i++) {
                sb.append("第").append(i + 1).append("条保存失败！原因:").append(errors.get(i).getMessage()).append("! ");
            }
            result.setMsg(sb.toString());
        }
        List<K3cBaseRet.ResultBean.ResponseStatusBean.SuccessEntitysBean> entitys = ret.getResult().getResponseStatus().getSuccessEntitys();
        if (null != entitys && entitys.size() > 0) {


            StringBuilder ids = new StringBuilder();
            StringBuilder numbers = new StringBuilder();
            for (K3cBaseRet.ResultBean.ResponseStatusBean.SuccessEntitysBean entity : entitys) {
                ids.append(entity.getId()).append(",");
                if (entity.getNumber() != null) {
                    numbers.append(entity.getNumber()).append(",");
                }
            }
            String id = ids.toString();
            K3cBase k3cBase = new K3cBase(id.substring(0, id.length() - 1));
            if (!"".equals(numbers.toString())) {
                k3cBase.setNumber(numbers.toString().substring(0, numbers.toString().length() - 1));
            }
            result.setData(k3cBase);
        } else {
            result.setData(new K3cBase(""));
        }
    }

    /**
     * 封装登录失败错误
     *
     * @param result JsonResult
     */
    private void packageLoginError(JsonResult<K3cBase> result) {
        result.setCode(RestfulErrorCode.LOGINERROR.getCode());
        result.setMsg(RestfulErrorCode.LOGINERROR.getMsg());
    }

    /**
     * 获取登录成功cookie
     */
    @SuppressWarnings("unchecked")
    public String getLoginCookie() throws Exception {
//        if (redisUtil.hasKey("k3c-login-cookie")) {
//            return (String) redisUtil.get("k3c-login-cookie");
//        }
        // 调用k3c登录获取cookie写入缓存
        String loginParam = k3cService.buildLogin(dbId, uid, pwd, lang);
        RetResult loginResult = k3cService.login(k3CloundConfig.getUrl() + k3CloundConfig.getLogin(), loginParam);
        if (!loginResult.getCode().equals(RestfulErrorCode.SUCCESS.getCode())) {
            throw new Exception("登录失败！");
        }
        // 取出登录cookie
        Map<String, Object> loginMap = (Map<String, Object>) loginResult.getData();
        String cookie = loginMap.get("cookie").toString();
//        redisUtil.set("k3c-login-cookie", cookie, 1800);
        return cookie;
    }
}